import config from '@/config/index';

// 请求拦截器
const requestInterceptor = (options) => {
  // 获取token
  const token = uni.getStorageSync('token');
  
  // 请求头
  options.header = {
    ...options.header,
    'Content-Type': 'application/json',
    'Authorization': token ? `Bearer ${token}` : ''
  };
  
  // 请求url
  if (!options.url.startsWith('http')) {
    options.url = config.baseUrl + options.url;
  }
  
  // 超时时间
  options.timeout = config.timeout;
  
  return options;
};

// 响应拦截器
const responseInterceptor = (response) => {
  const { statusCode, data } = response;
  
  // 请求成功
  if (statusCode >= 200 && statusCode < 300) {
    return data;
  }
  
  // 401: 未授权
  if (statusCode === 401) {
    // 清除token
    uni.removeStorageSync('token');
    uni.removeStorageSync('userInfo');
    
    // 跳转到登录页
    uni.navigateTo({
      url: '/pages/login/login'
    });
    
    return Promise.reject(new Error('未授权，请重新登录'));
  }
  
  // 其他错误
  return Promise.reject(data || new Error('网络请求错误'));
};

// 请求方法
const request = (options) => {
  return new Promise((resolve, reject) => {
    // 请求拦截
    options = requestInterceptor(options);
    
    // 发起请求
    uni.request({
      ...options,
      success: (res) => {
        try {
          // 响应拦截
          const result = responseInterceptor(res);
          resolve(result);
        } catch (error) {
          reject(error);
        }
      },
      fail: (err) => {
        uni.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
        reject(new Error('网络请求失败'));
      }
    });
  });
};

// 请求方法
const http = {
  get(url, params = {}, options = {}) {
    return request({
      url,
      method: 'GET',
      data: params,
      ...options
    });
  },
  
  post(url, data = {}, options = {}) {
    return request({
      url,
      method: 'POST',
      data,
      ...options
    });
  },
  
  put(url, data = {}, options = {}) {
    return request({
      url,
      method: 'PUT',
      data,
      ...options
    });
  },
  
  delete(url, data = {}, options = {}) {
    return request({
      url,
      method: 'DELETE',
      data,
      ...options
    });
  },
  
  upload(url, filePath, name = 'file', formData = {}, options = {}) {
    return new Promise((resolve, reject) => {
      const token = uni.getStorageSync('token');
      
      uni.uploadFile({
        url: config.baseUrl + url,
        filePath,
        name,
        formData,
        header: {
          'Authorization': token ? `Bearer ${token}` : ''
        },
        ...options,
        success: (res) => {
          if (res.statusCode >= 200 && res.statusCode < 300) {
            try {
              const data = JSON.parse(res.data);
              resolve(data);
            } catch (error) {
              resolve(res.data);
            }
          } else {
            reject(new Error('上传失败'));
          }
        },
        fail: (err) => {
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          });
          reject(new Error('上传失败'));
        }
      });
    });
  }
};

export default http;